package com.cll.pmis.filter;

import com.cll.pmis.common.security.SysUser;
import com.cll.pmis.config.UserFilterProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author chenliangliang
 * @date 2018/6/19
 */
@Slf4j
public class UserFilter extends OncePerRequestFilter {

    private AntPathMatcher pathMatcher;

    private String[] filterPaths;
    private String[] excludePaths;
    private String loginUrl;

    public UserFilter(AntPathMatcher pathMatcher,UserFilterProperties properties) {
        this.pathMatcher = pathMatcher;
        pathMatcher.setCachePatterns(true);
        String filterPath = properties.getPath();
        String excludePath = properties.getExclude();
        loginUrl=properties.getLoginUrl();
        if (StringUtils.isNotBlank(filterPath)) {
            filterPaths = StringUtils.split(filterPath, ",");
        } else {
            filterPaths = new String[]{"/**"};
        }

        if (StringUtils.isNotBlank(excludePath)){
            excludePaths=StringUtils.split(excludePath,",");
        }else {
            excludePaths=new String[]{};
        }
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        String contextPath=request.getContextPath();
        url=url.replace(contextPath,"");
        if (StringUtils.equals(loginUrl,url)){
            filterChain.doFilter(request,response);
            return;
        }
        for (String excludeUrl:excludePaths){
            if (pathMatcher.match(excludeUrl,url)){
                filterChain.doFilter(request, response);
                return;
            }
        }

        for (String path:filterPaths){
            if (pathMatcher.match(path,url)){
                HttpSession session = request.getSession();
                SysUser user = (SysUser) session.getAttribute("user");
                if (user==null){
                    log.warn("用户{}未登录",session.getId());
                    if (StringUtils.isNotBlank(loginUrl)){
                        response.sendRedirect(contextPath+loginUrl);
                        return;
                    }else {
                        request.setAttribute("error","您还未登录系统，请登录！");
                        request.getRequestDispatcher("/auth/error").forward(request,response);
                        return;
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
